/* <pre>
 * Copyright (c) The Loose Coupling Team.
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 *
 *      http://www.apache.org/licenses/LICENSE-2.0 
 *
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 *</pre>
 */
package org.lc.eic.synchronizer.request;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.lc.eic.api.requestreply.exception.RequestProcessingException;
import org.lc.eic.api.requestreply.sync.RequestDispatcher;
import org.lc.eic.synchronizer.request.impl.OngoingRequest;
import org.lc.eic.synchronizer.request.impl.OngoingRequestsHolder;
import org.lc.eic.synchronizer.request.status.RequestStatus;
import org.lc.eic.synchronizer.request.status.Status;



public class StatusRequestDispatcher implements RequestDispatcher<Object, Status> {
	
	private OngoingRequestsHolder ongoingRequestsHolder;	

	public Status request(Object request) throws RequestProcessingException {
		Map<String, OngoingRequest> ongoingRequests = ongoingRequestsHolder.getOngoingRequests();
		
		Status statusVO = new Status();
		
		List<RequestStatus> requests = new ArrayList<RequestStatus>();
		
		synchronized(ongoingRequests){
			
			statusVO.setTimestamp(new Timestamp(System.currentTimeMillis()));
			
			for (OngoingRequest oRequest : ongoingRequests.values()) {
				RequestStatus requestVO = new RequestStatus();
				requestVO.setCorrelationId(oRequest.getCorrelationID());
				requestVO.setExpirationTime(new Timestamp(oRequest.getExpirationTime().getTime()));
				requestVO.setUniqueID(oRequest.getUniqueID());
				requestVO.setRequest(oRequest.getRequest().toString());
				requests.add(requestVO);
			}		
			
		}
		statusVO.setRequests(requests);
		
		return statusVO;
		
		
	}



	public void setOngoingRequestsHolder(
			OngoingRequestsHolder ongoingRequestsHolder) {
		this.ongoingRequestsHolder = ongoingRequestsHolder;
	}

}
